import { _decorator, Component, EditBox, Node, UITransform } from 'cc';
import { ListRender } from './ListRender';
import { List } from './List';
import { TipsObjectType } from '../../Game/Config/GameEnum';
import { TipsManager } from '../Model/Tips/TipsManager';
const { ccclass, property, menu } = _decorator;

@ccclass('DropdownBox')
@menu('myComponent/DropdownBox')
export class DropdownBox extends Component {
  @property(EditBox)
  edit: EditBox;
  @property(List)
  list: List;

  private data;
  judgeFun: (input: string, data: unknown) => boolean;
  input: (data: unknown) => string;

  onEnable(): void {
    this.list.node.active = false;
  }

  setData(data) {
    this.data = data;
    if (this.data.length <= 0) return;
    if (this.input != null) {
      this.edit.string = this.input(this.data[0]);
    } else {
      this.edit.string = this.data[0].toString();
    }
  }

  onFocue() {
    this.onChange(this.edit.string);
    TipsManager.Singleton.showTips({
      type: TipsObjectType.flyTips,
      data: {
        node: this.list.node,
        form: this.node.getComponent(UITransform),
      },
    });
  }

  onChange(text) {
    if (this.judgeFun != null) {
      const arr = [];
      this.data.forEach((element) => {
        if (this.judgeFun(text, element)) {
          arr.push(element);
        }
      });
      this.list.setData(arr);
    }
  }

  onClick(...args) {
    const item: Node = args[0];
    const sp = item.getComponent(ListRender);
    if (this.input != null) {
      this.edit.string = this.input(sp.data);
    } else {
      this.edit.string = sp.data.toString();
    }
    TipsManager.Singleton.canelTip();
  }

  getEditString(): string {
    return this.edit.string;
  }
}
